package handlers

import (
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/gorilla/mux"
	"findata/auth"
	"findata/services"
)

// CreatePostWithTagsHandler 创建带标签的帖子
func CreatePostWithTagsHandler(w http.ResponseWriter, r *http.Request) {
	// 检查用户是否登录
	userID, err := auth.GetUserIDFromSession(r)
	if err != nil {
		http.Error(w, "未登录", http.StatusUnauthorized)
		return
	}

	// 解析请求体
	var req services.PostWithTagsRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "请求格式错误", http.StatusBadRequest)
		return
	}

	// 验证请求数据
	if req.Title == "" || req.Content == "" {
		http.Error(w, "标题和内容不能为空", http.StatusBadRequest)
		return
	}

	// 限制标签数量
	if len(req.Tags) > 5 {
		http.Error(w, "标签数量不能超过5个", http.StatusBadRequest)
		return
	}

	// 限制图片数量
	if len(req.Images) > 5 {
		http.Error(w, "图片数量不能超过5张", http.StatusBadRequest)
		return
	}

	// 创建帖子
	post, err := services.CreatePostWithTags(req, userID)
	if err != nil {
		http.Error(w, "创建帖子失败: "+err.Error(), http.StatusInternalServerError)
		return
	}

	// 返回成功响应
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"success": true,
		"id":      post.ID,
	})
}

// PostDetailHandler 获取帖子详情
func PostDetailHandler(w http.ResponseWriter, r *http.Request) {
	// 获取帖子ID
	vars := mux.Vars(r)
	idStr := vars["id"]
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		http.Error(w, "无效的帖子ID", http.StatusBadRequest)
		return
	}

	// 获取帖子详情
	post, err := services.GetPostDetail(uint(id))
	if err != nil {
		http.Error(w, "获取帖子失败: "+err.Error(), http.StatusInternalServerError)
		return
	}

	// 返回帖子详情
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(post)
} 